define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/admin_permission/index' + location.search,
                    add_url: 'scanwork/admin_permission/add',
                    edit_url: 'scanwork/admin_permission/edit',
                    del_url: 'scanwork/admin_permission/del',
                    multi_url: 'scanwork/admin_permission/multi',
                    import_url: 'scanwork/admin_permission/import',
                    table: 'admin',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'username', title: __('Username'), operate: 'LIKE'},
                        {field: 'nickname', title: __('Nickname'), operate: 'LIKE'},
                        {field: 'email', title: __('Email'), operate: 'LIKE'},
                        {field: 'mobile', title: __('Mobile'), operate: 'LIKE'},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden'),"1":__('Normal'),"0":__('Hidden')}, formatter: function(value, row, index) {
                            if (value === 'normal' || value === 1 || value === '1') {
                                return '<span class="text-success"><i class="fa fa-circle"></i> 正常</span>';
                            } else if (value === 'hidden' || value === 0 || value === '0') {
                                return '<span class="text-danger"><i class="fa fa-circle"></i> 禁用</span>';
                            } else {
                                return '<span class="text-warning"><i class="fa fa-circle"></i> ' + value + '</span>';
                            }
                        }},
                        {field: 'permission_count', title: '权限数量', operate: false, formatter: function(value, row, index) {
                            return '<span class="badge badge-info">' + (value || 0) + '</span>';
                        }},
                        {field: 'permissions', title: '权限列表', operate: false, formatter: function(value, row, index) {
                            if (!value || value.length === 0) {
                                return '<span class="text-muted">无权限</span>';
                            }
                            var html = '<div class="permission-list">';
                            for (var i = 0; i < Math.min(value.length, 3); i++) {
                                html += '<span class="badge badge-success">' + value[i] + '</span> ';
                            }
                            if (value.length > 3) {
                                html += '<span class="badge badge-default">+' + (value.length - 3) + ' 更多</span>';
                            }
                            html += '</div>';
                            return html;
                        }},
                        {field: 'logintime', title: __('Logintime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            $(document).on('click', '.btn-set-permissions', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要设置权限的管理员');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.warning('请选择一个管理员进行权限设置');
                    return;
                }
                
                Fast.api.open('scanwork/admin_permission/setPermissions/ids/' + ids[0], '设置权限', {
                    area: ['90%', '90%'],
                    callback: function(data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });

            // 必须绑定刷新事件
            $(document).on('click', '.btn-refresh', function () {
                table.bootstrapTable('refresh');
            });

            // 表格工具栏按钮事件
            $(document).on('click', '.btn-add', function () {
                Fast.api.open('scanwork/admin_permission/add', '添加管理员');
            });

            $(document).on('click', '.btn-edit', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要编辑的管理员');
                    return;
                }
                if (ids.length > 1) {
                    Toastr.warning('请选择一个管理员进行编辑');
                    return;
                }
                Fast.api.open('scanwork/admin_permission/edit/ids/' + ids[0], '编辑管理员');
            });

            $(document).on('click', '.btn-del', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要删除的管理员');
                    return;
                }
                
                Layer.confirm('确定要删除选中的管理员吗？', {icon: 3, title: '提示'}, function(index) {
                    Fast.api.ajax({
                        url: 'scanwork/admin_permission/del',
                        data: {ids: ids}
                    }, function(data, ret) {
                        table.bootstrapTable('refresh');
                        Layer.close(index);
                    });
                });
            });

            // 表格选择事件
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
                var ids = Table.api.selectedids(table);
                $('.btn-edit, .btn-del, .btn-set-permissions').toggleClass('disabled', ids.length === 0);
                $('.btn-edit').toggleClass('disabled', ids.length !== 1);
                $('.btn-set-permissions').toggleClass('disabled', ids.length !== 1);
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        setPermissions: function () {
            // 权限设置页面功能
            $(function() {
                // 全选/取消全选功能
                $('.permission-module').each(function() {
                    var $module = $(this);
                    var $checkboxes = $module.find('input[type="checkbox"]');
                    var $header = $module.find('h4');
                    
                    // 添加全选复选框
                    $header.append(' <input type="checkbox" class="module-select-all"> 全选');
                    
                    var $selectAll = $module.find('.module-select-all');
                    
                    // 全选功能
                    $selectAll.on('change', function() {
                        $checkboxes.prop('checked', $(this).prop('checked'));
                    });
                    
                    // 子复选框变化时更新全选状态
                    $checkboxes.on('change', function() {
                        var checkedCount = $checkboxes.filter(':checked').length;
                        $selectAll.prop('checked', checkedCount === $checkboxes.length);
                    });
                    
                    // 初始化全选状态
                    var checkedCount = $checkboxes.filter(':checked').length;
                    $selectAll.prop('checked', checkedCount === $checkboxes.length);
                });
                
                // 表单提交 - 使用FastAdmin标准方式
                Form.api.bindevent($('#add-form'));
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
